package com.example.utils;

import com.example.constant.DateConstant;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * Json工具类
 *
 */
@Slf4j
public class JsonUtil {
    private static ObjectMapper mapper;

    static {
        //jackson
        mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());

        //设置日期格式
        mapper.setDateFormat(new SimpleDateFormat(DateConstant.DEFAULT_DATE_TIME_FORMAT));

        //禁用空对象转换json
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //设置null值不参与序列化(字段不被显示)
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    /**
     * json字符串转对象
     */
    public static <T> T parse(String jsonStr, Class<T> clazz) {
        try {
            return mapper.readValue(jsonStr, clazz);
        } catch (Exception e) {
            //输出到日志文件中
            log.error(ErrorUtil.errorInfoToString(e));
        }
        return null;
    }

    /**
     * 对象转json字符串
     */
    public static String stringify(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            //输出到日志文件中
            log.error(ErrorUtil.errorInfoToString(e));
        }
        return null;
    }
    /**
     * 将对象转换为Map
     * @param obj 要转换的对象
     * @return 转换后的Map
     */
    public static Map<String, Object> objectToMap(Object obj) {
        try {
            // 将对象转换为JSON字符串
            String json = stringify(obj);
            // 将JSON字符串转换为Map
            return mapper.readValue(json, new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert object to map", e);
        }
    }

}
